package org.rebluh.hulunbuirtravelnetworkbackendframework.controller;


import jakarta.servlet.http.HttpSession;
import org.rebluh.hulunbuirtravelnetworkbackendframework.domain.User;
import org.rebluh.hulunbuirtravelnetworkbackendframework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 添加用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    // 根据邮箱获取用户
    @GetMapping("/email/{email}")
    public User getUserByEmail(@PathVariable("email") String email) {
        return userService.findByUsermail(email);
    }

    // 根据id获取用户
    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }

    // 邮箱密码登录
//    @PostMapping("/login")
//    public Boolean verifyAccount(@RequestParam String usermail, @RequestParam String password) {
//        return userService.verifyAccount(usermail, password);
//    }

    // 邮箱验证码登录
    @PostMapping("/login")
    public String verifyEmailCode(@RequestParam String email, @RequestParam String code, HttpSession session){
        if (userService.verifyEmailCode(email, code)){
            session.setAttribute("admin", true);
            session.setAttribute("username", email);
            return "success";
        } else return "fail";
    }

    // 验证登录
    @GetMapping("/login")
    public int login(HttpSession session) {
        Boolean isAdmin = (Boolean) session.getAttribute("admin");
        if (isAdmin != null && isAdmin) {
            return 1;
        } else {
            session.setAttribute("admin", false);
            return 0;
        }
    }

    //获取用户
    @GetMapping("/getUser")
    public User getUser(HttpSession session) {
        String email = (String) session.getAttribute("username");
        return userService.findByUsermail(email);
    }

    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("admin");
        if (session.getAttribute("admin") == null){
            return "1";
        }else return "2";
    }
}
